import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElNotification } from 'element-plus'
import { Cloud } from 'laf-client-sdk'
const APPID = 'su75ks' // Laf 应用 appid
const cloud = new Cloud({
  baseUrl: `https://${APPID}.laf.run`,
  getAccessToken: () => '',
})

export const useUserStore = defineStore(
  'user',
  () => {
    //定义数据state
    const userInfo = ref({
      name: '',
      create_date: 1,
      phone: '',
    })
    const info = ref({
      branch_name: '',
      create_date: '',
      college_id: '',
    })
    const token = ref('')
    const _id = ref('')
    const utype = ref()
    const Email = ref('')
    const num = ref('')
    const college_name = ref('')
    //定义获取接口数据的action函数
    //密码登录
    const loginByPw = async ({ email, password }) => {
      const res = await cloud.invoke('login', { email, password })
      if (res.code == 404) {
        ElNotification({
          message: '邮箱或密码不正确',
          type: 'error',
          duration: 3000,
        })
        return -1
      } else if (res.code == 200) {
        token.value = res.token
        utype.value = res.utype
        ElNotification({
          message: '欢迎来到智慧党建后台',
          type: 'success',
          duration: 1000,
        })
        Email.value = email
      }
      return 1
    }
    //退出时清除用户信息
    const clearUserInfo = () => {
      userInfo.value = {
        name: '',
        create_date: 1,
        phone: '',
      }
      info.value = {
        branch_name: '',
        create_date: '',
        college_id: '',
      }
      token.value = ''
      college_name.value = ''
      _id.value = ''
      num.value = ''
      utype.value = 0
      Email.value = ''
    }
    //导出数据
    return {
      token,
      _id,
      userInfo,
      num,
      utype,
      Email,
      info,
      college_name,
      loginByPw,
      clearUserInfo,
    }
  },
  {
    persist: true,
  },
)
